package ua.exchangeratesukraine.ui.fragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;

import ua.exchangeratesukraine.R;
import ua.exchangeratesukraine.actions.WorkDB;
import ua.exchangeratesukraine.model.CurrencyModel;
import ua.exchangeratesukraine.util.Constants;
import ua.exchangeratesukraine.util.Util;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListFragment;

public class FragmentBase extends SherlockListFragment implements OnClickListener, SetDataListener, OnTouchListener,
		OnItemSelectedListener {

	protected String					LOG_TAG				= getClass().getSimpleName();
	protected String					tableName			= "";
	protected Context					context				= null;
	protected TextView					tvCurrentDate		= null;
	protected TextView					tvSetBank			= null;
	protected Button					btnResult			= null;
	protected View						listHeader			= null;
	protected View						listFooter			= null;
	protected TextView					tvDate				= null;
	protected ProgressBar				bar					= null;
	protected BaseAdapter				adapter				= null;
	protected String					BASE_URL			= Constants.BASE_URL;
	protected String					WEB_ID				= Constants.WEB_ID;
	protected String					bank				= "";
	protected boolean					isListShow			= false;
	protected boolean					isDialogShow		= false;
	protected boolean					isNetworkAvailable	= false;
	protected boolean					isOneBank			= false;
	protected boolean					isRotate			= false;
	protected boolean					hasHeader			= false;
	protected boolean					isFragmentChange	= false;
	protected String					date				= "";
	protected String					prevDate			= "";
	protected ArrayList<CurrencyModel>	currencyModelArray	= new ArrayList<CurrencyModel>();
	protected ArrayList<String>			holidayMonthArray	= new ArrayList<String>();
	protected ArrayList<String>			holidayDayArray		= new ArrayList<String>();
	protected HashMap<String, String>	currency			= new HashMap<String, String>();

	protected int						touchUnitCount		= 0;
	protected int						touchChangeCount	= 0;
	protected int						touchAbsCount		= 0;
	protected int						touchRelCount		= 0;

	protected int						touchBuyCount		= 0;
	protected int						touchAbsBuyCount	= 0;
	protected int						touchAbsSaleCount	= 0;
	protected int						touchSaleCount		= 0;
	protected int						touchRelBuyCount	= 0;
	protected int						touchRelSaleCount	= 0;

	protected String					dbName				= "";
	protected String					state				= Constants.STATE_DEFAULT;
	protected String					currencyCode		= "";
	protected WorkDB					wdb					= null;
	protected int						position			= 0;
	protected long						currentTime			= 0;
	protected long						prevTime			= 0;

	@Override
	public void onCreate(Bundle inState) {
		context = getSherlockActivity();
		holidayMonthArray = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.holiday_month)));
		holidayDayArray = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.holiday_day)));
		super.onCreate(inState);
	}

	@Override
	public void onStart() {
		if(isListShow && !isRotate ){
			getListView().addHeaderView(listHeader);
			getListView().addFooterView(listFooter);
			hasHeader = true;
			initArray();
		}
		super.onStart();
	}

	@Override
	public void onStop() {
		setListAdapter(null);
		super.onStop();
	}
	
	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {}

	protected void fillTvCurrentDate(String date) {
		tvCurrentDate.setText(date);
	}

	protected void fillTvDate(String date) {
		tvDate.setText(date);
	}

	protected String getCurrentDate() {
		Calendar sDate = Calendar.getInstance();
		Log.d(LOG_TAG, "YEAR = " + sDate.get(Calendar.YEAR) + "; MONTH = " + (sDate.get(Calendar.MONTH) + 1)
				+ "; DAY_OF_MONTH = " + (sDate.get(Calendar.DAY_OF_MONTH)));
		return ""
				+ sDate.get(Calendar.YEAR)
				+ "-"
				+ (((sDate.get(Calendar.MONTH) + 1) > 9) ? (sDate.get(Calendar.MONTH) + 1) : (("0" + (sDate
						.get(Calendar.MONTH) + 1))))
				+ "-"
				+ ((sDate.get(Calendar.DAY_OF_MONTH) > 9) ? sDate.get(Calendar.DAY_OF_MONTH) : ("0" + sDate
						.get(Calendar.DAY_OF_MONTH)));

	}

	protected void showDateDialog() {
		DateDialogFragment datePicker = DateDialogFragment.newInstance(getActivity());
		datePicker.setDateDialogFragmentListener(new DateDialogFragmentListener() {
			@Override
			public void dateDialogFragmentDateSet(int year, int monthOfYear, int dayOfMonth) {
				int month = monthOfYear + 1;
				date = year + "-" + ((month > 9) ? month : ("0" + month)) + "-"
						+ ((dayOfMonth > 9) ? dayOfMonth : ("0" + dayOfMonth));
				Log.d(LOG_TAG, "date = date");
				fillTvCurrentDate(date);
			}
		});
		datePicker.show(getActivity().getSupportFragmentManager(), "date picker dialog fragment");
	}

	@SuppressWarnings("unchecked")
	@Override
	public void setData(Object result, Bundle inState, String state) {
		String connectionError = getString(R.string.text_toast_connection_error);
		String urlConnectionError = getString(R.string.text_toast_url_connection_error);
		if ((result.toString()).equals(connectionError)) {
			showToast(getString(R.string.title_toast_connection_error), connectionError, 0);
			return;
		} else if ((result.toString()).equals(urlConnectionError)) {
			showToast(getString(R.string.title_toast_connection_error), urlConnectionError, 0);
			return;
		} else if ((result.toString()).equals(Constants.REQUESTS_LIMIT)) {
			showToast(getString(R.string.title_toast_url_connection_error), urlConnectionError, 0);
			return;
		}
		currencyModelArray = (ArrayList<CurrencyModel>) result;

		if (isOneBank)
			setCurrencyModelArray(getDataForOneBank(currencyModelArray));
		
		setListAdapter(null);

		if (currencyModelArray.isEmpty()) {

			getListView().removeHeaderView(listHeader);
			getListView().removeFooterView(listFooter);
			hasHeader = false;
			fillTvDate("");
			isListShow = false;
			showToast(getString(R.string.title_toast_attention), 
					getString(R.string.text_array_empty_date), 0);
			return;
		}
		
		if (!isListShow) {
			getListView().addHeaderView(listHeader);
			getListView().addFooterView(listFooter);
		}
		
		setCurrencyName(currencyModelArray); // for NBU

		long currentTime = Util.getCurrentTime();
		long requestTime = Util.stringToLong(date);
		long timeDiff = currentTime - requestTime;
		
		String tableName = getTableName();
		if (state.equals(Constants.STATE_FROM_SERVER) && !currencyModelArray.isEmpty()){
			if(tableName.equals(Constants.TABLE_NAME_BANKS) && timeDiff > Constants.CHECK_TIME_DIF )
				wdb.addToDB(currencyModelArray, date, tableName, currencyCode);
			
			if(tableName.equals(Constants.TABLE_NAME_NBU))
				wdb.addToDB(currencyModelArray, date, tableName, currencyCode);
		}

		if(currencyModelArray.size() > 1 )
			sort((TextView) getActivity().findViewById(R.id.tvNameCurrencyUnit), true);
		prevDate = date;
		hasHeader = true;
		initArray();
	}

	protected void initArray() {
		adapter = getAdapter();
		setListAdapter(adapter);
		adapter.notifyDataSetChanged();
		fillTvDate(" " + getString(R.string.text_on_date) + " " + prevDate);
		isListShow = true;
	}
	
	protected void setCurrencyModelArray(ArrayList<CurrencyModel> currencyModelArray){
		this.currencyModelArray = currencyModelArray;
	}

	protected ArrayList<CurrencyModel> getDataForOneBank(ArrayList<CurrencyModel> currencyModelArray) {
		return this.currencyModelArray;
	}
	
	protected void setIsOneBank(boolean isOneBank) {
		this.isOneBank = isOneBank;
	}

	protected boolean getIsOneBank() {
		return false;
	}

	protected String getTableName() {
		return "";
	}

	protected void setCurrencyName(ArrayList<CurrencyModel> currencyModelArray) {
	}

	protected void setBanksName(ArrayList<CurrencyModel> currencyModelArray) {
	}

	protected BaseAdapter getAdapter() {
		return null;
	}

	@Override
	public void setProgressVisible() {
		bar.setVisibility(View.VISIBLE);
	}

	@Override
	public void setProgressInVisible() {
		bar.setVisibility(View.INVISIBLE);
	}

	@Override
	public boolean onTouch(View v, MotionEvent motionEvent) {
		switch (motionEvent.getAction()) {
			case MotionEvent.ACTION_DOWN:
				if (v.getId() == R.id.btnResult) {
					btnResult.setBackgroundResource(R.drawable.button_nbu_pressed);
					btnResult.setTextColor(Color.WHITE);
				}
				if (v.getId() == R.id.tvSetBank) {
					tvSetBank.setBackgroundResource(R.drawable.tv_current_date_pressed);
					tvSetBank.setTextColor(Color.WHITE);
				}
				if (v.getId() == R.id.tvCurrentDate) {
					tvCurrentDate.setBackgroundResource(R.drawable.tv_current_date_pressed);
					tvCurrentDate.setTextColor(Color.WHITE);
				}
				break;
			case MotionEvent.ACTION_CANCEL:
			case MotionEvent.ACTION_UP:
				if (v.getId() == R.id.btnResult) {
					btnResult.setBackgroundResource(R.drawable.button_nbu_normal);
					btnResult.setTextColor(Color.DKGRAY);
				}
				if (v.getId() == R.id.tvSetBank) {
					tvSetBank.setBackgroundResource(R.drawable.tv_current_date_normal);
					tvSetBank.setTextColor(Color.DKGRAY);
				}
				if (v.getId() == R.id.tvCurrentDate) {
					tvCurrentDate.setBackgroundResource(R.drawable.tv_current_date_normal);
					tvCurrentDate.setTextColor(Color.DKGRAY);
				}
				break;
		}
		return false;
	}

	protected void showToast(String title, String message, int duration) {
		LayoutInflater inflater = getLayoutInflater(null);
		View layoutToast = inflater.inflate(R.layout.toast, (ViewGroup) getView().findViewById(R.id.layoutToast));
		TextView tvTitleToast = (TextView) layoutToast.findViewById(R.id.tvTitleToast);
		tvTitleToast.setText(title);
		TextView tvTextToast = (TextView) layoutToast.findViewById(R.id.tvTextToast);
		tvTextToast.setText(message);

		Toast toast = new Toast(context);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setView(layoutToast);
		toast.setDuration(duration);
		toast.show();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		setListAdapter(null);
	}

	protected ArrayList<CurrencyModel> getCurrencyModelArray() {
		return currencyModelArray;
	}

	public void sortFragment(View view, boolean isFirstRequest) {}

	protected void sort(View view, boolean isFirstRequest) {}
	
	@Override
	public void onClick(View view) {}

	protected void getDataFromDB() {}

	protected boolean checkDate() {
		boolean isFutureTime = Util.isTimeFuture(date);
		if (isFutureTime) {
			showToast(getString(R.string.title_toast_attention), 
					getString(R.string.text_day_no_present), 0);
			return isFutureTime;
		}

		Util.checkHoliday(holidayMonthArray, holidayDayArray, date);
		if (!date.equals(Util.date))
			date = Util.date;

		Util.checkDayOff(holidayMonthArray, holidayDayArray, date);
		if (!date.equals(Util.date))
			date = Util.date;

		return isFutureTime;
	}

	public boolean isFragmentChange() {
		return isFragmentChange;
	}

	public void setFragmentChange(boolean isFragmentChange) {
		this.isFragmentChange = isFragmentChange;
	}
}